package common.database.implementations;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import common.database.bean.Page;

public class MySqlDAOImpl<T> extends BaseDAOImpl<T>{
	@Autowired
	private JdbcTemplate mySqlJdbcTemplate;

	@Override
	public Page getListByPage(String sql, Page page, Class<T> returnType,
			Object... values) throws Exception{

		// LOG.debug("===findByPage===sql=====" + sql);
		StringBuffer totalSQL = new StringBuffer(" SELECT count(*) FROM ( ");
		totalSQL.append(sql);
		totalSQL.append(" ) totalTable ");
		int totalCount = getJdbcTemplate().queryForInt(totalSQL.toString(),
				values);

		StringBuffer paginationSQL = new StringBuffer();
		paginationSQL.append(sql);
		paginationSQL.append( " LIMIT "+page.getStart()+","+page.getPageSize());

		List result = this
				.getList(paginationSQL.toString(), returnType, values);
		page.setResult(result);
		page.setTotalCount(totalCount);
		return page;
	
//		sql.append("SELECT *FROM "+entityClass.getSimpleName()+"LIMIT"+(pageNo-1)*pageSize);
//		return null;
	}
	
	public String monitor() throws SQLException {
		DataSource ds = mySqlJdbcTemplate.getDataSource();
		if(ds instanceof ComboPooledDataSource){
			ComboPooledDataSource dp = (ComboPooledDataSource)ds;
			StringBuffer sb = new StringBuffer();
			sb.append("num_connections: "+ dp.getNumConnectionsDefaultUser()+",");
			sb.append("num_busy_connections: "+ dp.getNumBusyConnectionsDefaultUser()+",");
			sb.append("num_idle_connections: "+ dp.getNumIdleConnectionsDefaultUser()+",");
			return sb.toString();
		}else{
			return "";
		}
	}
}
